package cn.yunyichina.provider.clinic.thread;

import java.math.BigDecimal;
import java.util.*;

import cn.yunyichina.provider.iface.entity.common.Response;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.clinic.constant.CacheConstant;
import cn.yunyichina.provider.clinic.manager.ClinicBizManager;
import cn.yunyichina.provider.clinic.vo.ListMzfeeVoResponse;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.OrderListVo;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.hisiface.clinic.FeeDetailVoResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;

public class QueryAndSaveMzDetailRunnable implements Runnable {

    private Logger logger = LoggerFactory.getLogger(QueryAndSaveMzDetailRunnable.class);

    private List<OrderExtVo> orders;

    private String sessionId;

    /*
     * null -- 海鹚
     * 1 -- 智慧医院
     * 2 -- 云医宝
     */
    private Integer isFromInner;

    public QueryAndSaveMzDetailRunnable() {
        super();
    }

    public QueryAndSaveMzDetailRunnable(String sessionId, List<OrderExtVo> orders, Integer isFromInner) {
        this.sessionId = sessionId;
        this.orders = orders;
        this.isFromInner = isFromInner;
    }

    @Override
    public void run() {
        String userInfoJson = CacheService.getSessionKey(sessionId, CacheConstant.CACHE_SESSION_USER);
        SessionInfo userInfo = JsonUtils.parseObject(userInfoJson, SessionInfo.class);

        ClinicBizManager clinicBizManager = (ClinicBizManager) SpringContextHandler.getBean("clinicBizManager");

        for (OrderExtVo orderExtVo : orders) {
            JSONObject extraParamsMap = JsonUtils.parseObject(orderExtVo.getExtraParams());
            ListMzfeeVoResponse mzFee = new ListMzfeeVoResponse();
            mzFee.setHospitalCode(orderExtVo.getOrgCode());
            mzFee.setBranchCode(orderExtVo.getBranchCode());
            mzFee.setMzFeeId(extraParamsMap.getString("mz_fee_id"));
            mzFee.setPatCardType(orderExtVo.getMedicalCardType().intValue());
            mzFee.setPatCardNo(orderExtVo.getMedicalCardNo());
            mzFee.setDeptCode(orderExtVo.getDeptCode());
            mzFee.setDoctorCode(orderExtVo.getDoctorCode());
            mzFee.setTime(orderExtVo.getCreatedTime());
            mzFee.setPatCardNo(orderExtVo.getMedicalCardNo());
            List<FeeDetailVoResponse> list = clinicBizManager.getMZFeeDetail(mzFee, userInfo, "");
            logger.info("门诊待缴费明细线程, 就诊卡号" + mzFee.getPatCardNo() + ", 门诊流水号" + mzFee.getMzFeeId() + ", 待缴费明细列表list="
                    + JSON.toJSONString(list));
            if (CollectionUtils.isNotEmpty(list)) {
                //查询订单
                Map<String, String> ordQueryDataMap = new HashMap<String, String>();
                ordQueryDataMap.put("order_no", orderExtVo.getOrderNo());
                logger.info("【门诊待缴费明细线程-查询订单信息】, yyt.base.order.by.order.no.out.get request=" + JSON.toJSONString(ordQueryDataMap));
                Response ordQueryResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.order.no.out.get",
                        JsonUtils.toJsonString(ordQueryDataMap));
                logger.info("【门诊待缴费明细线程-查询订单信息】, yyt.base.order.by.order.no.out.get response=" + JSONObject.toJSONString(ordQueryResponse));
                OrderExtVo qureyOrderExtVo = null;
                if ("0".equals(ordQueryResponse.getResultCode())) {
                    qureyOrderExtVo = JsonUtils.parseObject(ordQueryResponse.getResult(), OrderExtVo.class);
                }

                List<OrderListVo> orderLists = new ArrayList<OrderListVo>();
                for (FeeDetailVoResponse mzFeeDetail : list) {
                    OrderListVo orderList = new OrderListVo();
                    orderList.setCreatedTime(DateUtils.dateToString(new Date()));
                    orderList.setGoodsId(mzFeeDetail.getItemId());
                    orderList.setGoodsName(mzFeeDetail.getItemName());
                    orderList.setGoodsPrice(StringUtils.isNotBlank(mzFeeDetail.getItemPrice())
                            ? Double.parseDouble(mzFeeDetail.getItemPrice()) : 0);
                    orderList.setGoodsQty(StringUtils.isNotBlank(mzFeeDetail.getItemNumber())
                            ? Double.parseDouble(mzFeeDetail.getItemNumber()) : 0);
                    orderList.setGoodsSpec(mzFeeDetail.getItemSpec());
                    orderList.setGoodsUnit(mzFeeDetail.getItemUnit());
                    orderList.setGoodsConsumption(mzFeeDetail.getItemDose());
                    orderList.setGoodsUsage(mzFeeDetail.getItemUsage());
                    orderList.setGoodsFrequency(mzFeeDetail.getItemFrequency());
                    orderList.setGoodsApprovalNo(mzFeeDetail.getDrugApprovalNumber());
                    orderList.setGoodsSocialInsuranceId(mzFeeDetail.getSocialInsuranceItemId());
                    orderList.setId(PKGenerator.generateId());

                    if(qureyOrderExtVo != null && StringUtils.isNotBlank(qureyOrderExtVo.getId())){
                        //修复为ord_order表的id作为orderid的值
                        orderList.setOrderId(qureyOrderExtVo.getId());
                    }else{
                        if (isFromInner != null && 1 == isFromInner.intValue()) {
                            // 新平台订单YPA
                            orderList.setOrderId(CacheService.generateOrderNum(2, 3));
                        } else if (isFromInner != null && 2 == isFromInner.intValue()) {
                            orderList.setOrderId(CacheService.generateOrderNum(2, 3));
                        } else {
                            // 其他都为YCP
                            orderList.setOrderId(CacheService.generateOrderNum(2, 1));
                        }
                    }

                    orderList.setOrderNo(orderExtVo.getOrderNo());
                    BigDecimal price = new BigDecimal(Double.toString(orderList.getGoodsPrice()));
                    BigDecimal qty = new BigDecimal(Double.toString(orderList.getGoodsQty()));

                    orderList.setTotGoodsMoney(price.multiply(qty).doubleValue());
                    orderList.setTotRealGoodsMoney(price.multiply(qty).doubleValue());


                    if(StringUtils.isNotBlank(mzFeeDetail.getPayFlag())){
                        //增加扩展参数
                        //payFlag;//0为可缴费，1为不可缴费
                        Map<String,String> listExtraParams = new HashMap<>();
                        String canPay = "1";
                        if("1".equals(mzFeeDetail.getPayFlag())){
                            canPay = "0";
                        }
                        listExtraParams.put("can_pay",canPay);
                        listExtraParams.put("his_record_time",mzFeeDetail.getItemTime());
                        orderList.setExtraParams(JsonUtils.toJsonString(listExtraParams));
                    }

                    orderLists.add(orderList);
                }

                try {
                    logger.info("门诊待缴费明细线程, 就诊卡号" + mzFee.getPatCardNo() + ", 门诊流水号" + mzFee.getMzFeeId()
                            + ", 调用base模块, 批量添加订单明细接口入参request=" + JSON.toJSONString(orderLists));
                    Response addOrdListResponse = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.order.list.out.add",
                            JsonUtils.toJsonString(orderLists));
                    if ("0".equals(addOrdListResponse.getResultCode())){
                        //如果是外购处方单，则进行药品匹配
                        if(OrderExtVo.ORDER_TYPE_CLINIC_BUY_OUT.equals(orderExtVo.getOrderType())){
                            Thread drugMatchedRunnable = new Thread(
                                    new DrugMatchedRunnable(sessionId, orderExtVo.getOrderNo()));
                            drugMatchedRunnable.start();
                        }
                    }else{
                        logger.error("门诊待缴费明细线程, 就诊卡号" + mzFee.getPatCardNo() + ", 门诊流水号" + mzFee.getMzFeeId()
                                + ", 调用base模块, 批量添加订单明细接口失败!", addOrdListResponse.getResultMessage());
                    }
                } catch (Exception ex) {
                    logger.error("门诊待缴费明细线程, 就诊卡号" + mzFee.getPatCardNo() + ", 门诊流水号" + mzFee.getMzFeeId()
                            + ", 调用base模块, 批量添加订单明细接口失败!", ex);
                    throw new CallException("3000", "QueryAndSaveMzDetailRunnable, 添加门诊缴费明细失败!", ex);
                }
            }
        }
    }
}
